import type { ComponentStyleIdType } from '../../../types/interfaces'
import { ScrollButton } from '../../../components/scroll_button'
import { ScrollDirection } from '../../../components/scroll_button/types'
import { BaseModule } from '../../../lib/abstract'
import { BodyHandler } from '../../../lib/body_handler'
import { ToolKit } from '../../../lib/utils/toolkit'
import { ComponentStyleId, EVENT_EMITTER_NAMES, logger } from '../../../types/constants'
import { ConfigManager } from '../../config_manager'
import { AppModule } from '../../config_manager/types'
import { StyleManager } from '../../style_manager'

interface Config {
  enabled?: boolean
  direction?: ScrollDirection
}

export class QuickScroll extends BaseModule {
  readonly id: string = 'quick_scroll'
  readonly styleId: string = ComponentStyleId[this.name]
  isInitialized: boolean = false
  private static instance: QuickScroll
  private readonly configManager: ConfigManager = ConfigManager.getInstance()
  readonly supportedPlatforms: string[] = this.configManager.moduleSupportedPlatforms(this.name)
  private readonly eventId: string = EVENT_EMITTER_NAMES.refreshQuickScroll
  scrollButton: ScrollButton | null = null
  isRendered: boolean = false
  forceShow: boolean = false

  config: Config = {
    enabled: true,
    direction: ScrollDirection.Top,
  }

  get name(): ComponentStyleIdType {
    return 'QuickScroll'
  }

  constructor() {
    super()

    if (this.config.enabled && this.configManager.getFeatureEnabled(AppModule.QuickScroll.id)) {
      this.registerEventListener()
    }
  }

  /**
   * 获取单例实例
   */
  public static getInstance(): QuickScroll {
    if (!QuickScroll.instance) {
      QuickScroll.instance = new QuickScroll()
    }
    return QuickScroll.instance
  }

  handleCleanupEventListeners(): void {
    super.handleCleanupEventListeners()

    this.unregisterEventListener()
  }

  handleCleanupReferences(): void {
    // 1. 移除滚动按钮
    if (this.scrollButton) {
      this.scrollButton.destroy()
      this.scrollButton = null
    }
  }

  handleCleanupOthers(): void {
    this.isRendered = false
  }

  core(): void {
    this.loadConfig()

    if (!this.config.enabled)
      return

    this.renderScrollButton()

    // 注册样式
    StyleManager.getInstance().registerStyle(this.styleId, this.getStyles(), false, true)
  }

  onToggleCallback(_id: string, checked: boolean, first: boolean): void {
    this.forceShow = !first && checked

    super.onToggleCallback(_id, checked, first)
  }

  registerEventListener(): void {
    this.eventEmitter.on(this.eventId, () => {
      const isScrollable = BodyHandler.checkScrollable()

      if (!isScrollable)
        this.destroy()

      if (!this.isRendered)
        this.core()
    })
  }

  unregisterEventListener(): void {
    this.eventEmitter.off(this.eventId)
  }

  renderScrollButton(): void {
    this.scrollButton = new ScrollButton({
      id: 'quick-scroll',
      direction: this.config.direction || ScrollDirection.Top,
      forceShow: this.forceShow,
    })

    const html = this.scrollButton.render()
    const $container = $('body')

    // 先渲染
    $container.append(html)
    // 再挂载
    this.scrollButton.mount($container)
    // 标记为项目元素
    ToolKit.browser.platform.markProjectElement(this.scrollButton?.$element)
    // 检查是否渲染成功
    this.isRendered = $(`.${this.scrollButton.className}`).length > 0
  }

  applyConfig(config: Partial<Config>): void {
    super.updateConfig(config)

    this.renderScrollButton()

    logger.info(`[${this.name}] Config updated and apply`, this.config)
  }

  getStyles(): string {
    return ``
  }
}
